<template>
  <el-form-item :class="getClz(['upload-img'])" :label="opt.text" :prop="opt.name" v-if="!opt.hide" size="mini">
    <el-upload
      class="upload-demo noupload"
      multiple
      listType="picture-card"
      :on-preview="handlePreview"
      :show-file-list="opt.showFile"
      disabled
      :file-list="fileList"
      action=""
    >
      <el-button size="mini" type="primary">{{opt.buttonText}}</el-button>
      <div slot="tip" class="el-upload__tip" v-show="Boolean(opt.showTips)">{{opt.showTips}}</div>
    </el-upload>
  </el-form-item>
</template>

<script>
  import extend from '../extend';

  const defaultOpt = {
    showTips:"",
    showFile:true,
    name:'',
    text:'',
    className:'',
    fileSize:3, // M
    limit:1,
    loading:false,
    buttonText:"上传文件",
    props:{
      accept:'',
      disabled:false
    }
  }

  export default {
    name: "FormTextImg",
    mixins:[extend],
    data(){
      return {
        showFile:false,
        fileList:[],
        opt:{...defaultOpt}
      }
    },
    methods: {
      setOpt(conf) {
        _.assign(this.opt, defaultOpt, conf);
        this.showFile = this.opt.showFile;
        this.setValue(conf.value);
      },
      setValue(list) {
        let res = this.setValueMap(list);
        this.fileList = res;
        this.$forceUpdate();
      },
      setValueMap(list = []){
        if(Object.prototype.toString.call(list) == "[object String]"){
          list = [{name:list.replace(/.*\/(.*)/,'$1'),url:list}]
        }
        //
        this.data[this.opt.name] = list;
        return list;
      },
      handleRemove(file) {
        let idx = _.findIndex(this.fileList, file);
        this.fileList.splice(idx, 1);
        this.setValueMap(this.fileList);
      },
      handlePreview(file) {
        //console.log(file);
        window.open(file.url);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 ${this.opt.limit}个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      upload({file}) {
        if(this.opt.onUpload){
          const blob = new Blob([file], {type: file.type});
          const fileUrl = window.URL.createObjectURL(blob);
          this.fileList.push({name: file.name, url: fileUrl,file:file});
          this.setValueMap(this.fileList);
          this.opt.onUpload(this.fileList,this.data);
          return;
        }
        //
        this.api("base.upload",{file}).then((res)=>{
          let data = res.data;
          this.fileList.push({name: file.name, url: data.url,smallUrl:data.smallUrl,imgId:data.imgId});
          this.setValueMap(this.fileList);
        })
      },
    }
  }

</script>

<style lang="scss">

</style>
